// pages/pay/monthly/monthly.js
const app = getApp()
const request = require("../../../utils/request.js");
let config = require('../../../config/config.js')
var QQMapWx = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWx({
  key: config.map_key
})

Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    screenHeight: app.globalData.screenHeight,
    showSearchDialog: false,
    searchResult: [],
    searchResultDiy: [],
    searcheVip: {},
    nowParkList: [],
    checkParkList: [],
    allParkList: [],
    diyCardList: [],
    // diyCardList: [{
    //   name: '月卡',
    //   money: '',
    //   time: '30',
    //   select: true
    // },
    // {
    //   name: '季卡',
    //   money: '',
    //   time: '90',
    //   select: false
    // },
    // {
    //   name: '年卡',
    //   money: '',
    //   time: '365',
    //   select: false
    // }],
    agreementVip: true,
    totalPay: 0,
    cardIndex: 0,
    nearbyParkList: [],
    verifyLoginDialog: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let token = wx.getStorageSync('lmtc_token');
    if (token) {
      this.getUserInfo()
    } else {
      this.setData({
        verifyLoginDialog: true
      })
    }
  },
  verifyLogin() {
    this.getUserInfo()
  },
  /**
 * 底部弹窗弹出
 */
  showBottomPop() {
    if (this.data.checkParkList.length >= 5) {
      wx.showToast({
        title: '最多选择五个停车场',
        icon: 'none'
      })
      return
    }
    let searcheRecordDiy = wx.getStorageSync('searcheRecordDiy');
    if (searcheRecordDiy != null) {
      this.setData({
        searcheRecordDiy: searcheRecordDiy
      })
    }
    let searcheVip = wx.getStorageSync('searcheVip');
    if (searcheVip != null) {
      this.setData({
        searcheVip: searcheVip
      })
    }
    this.setData({
      showSearchDialog: true
    })
  },
  /**
   * 底部弹窗关闭
   */
  hiddenSearchDialog() {
    this.setData({
      showSearchDialog: false,
      isPackaging: false,
      isNotSearchData: false,
      searchAddress: '',
      searchResultDiy: [],
    })
  },
  /**
   * 获取搜索输入框的文字
   */
  getSearch(event) {
    let that = this
    this.setData({
      searchAddress: event.detail.value
    })
    // this.searchStopPark(event.detail.value)
    qqmapsdk.getSuggestion({
      keyword: event.detail.value,
      region: this.data.city,
      page_size: 10,
      success(res) {
        var data = res.data
        that.setData({
          searchResultDiy: data,
          searchResult: [],
          isNotSearchData: false
        })
        if (data.length <= 0) {
          that.setData({
            isNotSearchData: true
          })
        }
      }
    })
  },
  searchStopPark(val) {
    let that = this
    if (!val) {
      that.setData({
        searchPark: []
      })
      return
    }
    let url = '/park/info/getParkByName'
    let params = {
      keyword: val
    }
    request.http(url, 'GET', params)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          that.setData({
            searchPark: data.data
          })
        }
      })
  },
  /**
 * 获取用户当前位置
 */
  getUserLocation() {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        let longitude = res.longitude;
        let latitude = res.latitude;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        });
        //获取全部停车场
        that.getParks(longitude, latitude);
        that.getLocal(latitude, longitude);
      }
    })
  },
  /**
   * 获取当前地理位置
   * @param {Number} latitude 纬度
   * @param {Number} longitude 经度
   */
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city
        })

      },
      fail: function (res) {
        Toast.fail('获取位置失败，请重新登录');
      }
    });
  },
  /**
   * 计算两点之间距离
   * @param {Object} from 起始点经纬度
   * @param {Array} to 结束点经纬度
   * @param {Function} callback 回调函数
   */
  calculateDistance(from, to, callback) {
    qqmapsdk.calculateDistance({
      mode: 'driving',
      from,
      to,
      success(res) {
        callback(res)
      },
      fail: function (error) {
        console.error(error);
      },
    })
  },
  /**
   * 获取附近停车场
   * @param {*} longitude 经度
   * @param {*} latitude 纬度
   */
  getParks(longitude, latitude) {
    let that = this;
    let record = {
      longitude: longitude,
      latitude: latitude,
      currentPage: 1,
      pageSize: 5
    }
    let url = "/park/info/getNearbyParkList";
    request.http(url, 'GET', record)
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data.records;
          that.calculateDistance({
            longitude: longitude,
            latitude: latitude
          },
            [{
              longitude: parkList[0].longitude,
              latitude: parkList[0].latitude
            }],
            function (res) {
              parkList[0].distances = (res.result.elements[0].distance / 1000).toFixed(2)
              console.log(parkList);
              that.setData({
                nearbyParkList: parkList,
                nowParkList: parkList[0]
              })
              // that.getMonthPayRule();
            }
          )
        }
      })
  },
  showMapMark(e) {
    let that = this
    let nearbyParkLists = this.data.nearbyParkList
    let index = e.currentTarget.dataset.index
    let nearbyParkList = nearbyParkLists[index]
    let selctPark = nearbyParkList
    let checkParkList = this.data.checkParkList
    for (var i = 0; i < checkParkList.length; i++) {
      if (selctPark.id == checkParkList[i].id) {
        wx.showToast({
          title: '请不要选择重复停车场',
          icon: 'none'
        })
        return
      }
    }
    checkParkList = checkParkList.concat(selctPark)
    if (checkParkList.length > 5) {
      Toast('最多选择五个停车场')
      return
    }
    this.setData({
      checkParkList: checkParkList
    })
    if (checkParkList.length > 1) {
      this.calculateDiyPrice()
    } 
    // else {
    //   this.getMonthPayRule(checkParkList[0].id)
    // }
    this.hiddenSearchDialog()
  },
  selectSearchPark(e) {
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let mold = e.currentTarget.dataset.mold
    if (type == 'history') {
      this.getNearbyPark(e.currentTarget.dataset.lng, e.currentTarget.dataset.lat)
    } else {
      let searchResultDiy
      let record = {}
      if (mold == 'park') {
        searchResultDiy = this.data.searchPark
        record = {
          place: searchResultDiy[index].parkName,
          latitude: searchResultDiy[index].latitude,
          longitude: searchResultDiy[index].longitude,
          address: searchResultDiy[index].parkAddress
        }
      } else if (mold == 'address') {
        searchResultDiy = this.data.searchResultDiy
        record = {
          place: searchResultDiy[index].title,
          latitude: searchResultDiy[index].location.lat,
          longitude: searchResultDiy[index].location.lng,
          address: searchResultDiy[index].address
        }
      }
      var searcheVip = wx.getStorageSync('searcheVip');
      if (Array.isArray(searcheVip)) {
        if (searcheVip.length == 2) {
          searcheVip.splice(1, 1);
          searcheVip.unshift(record);
        } else {
          searcheVip.unshift(record);
        }
      } else {
        searcheVip = [];
        searcheVip.push(record);
      }
      wx.setStorageSync('searcheVip', searcheVip);
      this.getNearbyPark(record.longitude, record.latitude)
    }
    this.setData({
      searchResultDiy: []
    })
  },
  /**
 * 获取附近停车点
 * @param {Number} longitude 经度
 * @param {Number} latitude 纬度
 */
  getNearbyPark(longitude, latitude) {
    let that = this
    let record = {
      longitude: longitude,
      latitude: latitude,
      currentPage: 1,
      pageSize: 10
    }
    let url = "/park/info/get-nearby-park-has-month-rule-list";
    if (this.data.tabbarIndex == 1) {
      url = "/park/info/getNearbyParkList";
    }
    request.http(url, 'GET', record)
      .then((res) => {
        if (res.data.code == 200) {
          let parkList = res.data.data.records;
          if (parkList.length <= 0) {
            wx.showToast({
              title: '当前地点附近暂无停车场可用',
              icon: 'none'
            })
          }
          that.setData({
            searchResult: parkList
          })
        }
      })
  },
  /**
  * 删除已经选择的停车场
  */
  deleCheckPark(event) {
    let index = event.currentTarget.dataset.index;
    let that = this;
    let allParkList = that.data.allParkList;
    let diyCardList = that.data.diyCardList;
    let checkParkList = that.data.checkParkList;
    for (let i = 0; i < allParkList.length; i++) {
      if (allParkList[i].id == checkParkList[index].id) {
        allParkList[i].select = false
      }
    }
    for (let i = 0; i < diyCardList.length; i++) {
      diyCardList[i].select = false
    }
    checkParkList.splice(index, 1);
    that.setData({
      checkParkList: checkParkList,
      allParkList: allParkList,
      diyCardIndex: 0

    })
    if (checkParkList.length > 1 ) {
      that.calculateDiyPrice();
    } 
    // else {
    //   that.getMonthPayRule(checkParkList[0].id)
    // }
    if (checkParkList.length <= 0) {
      that.setData({
        diyCardList: [{
          name: '月卡',
          money: '',
          time: '30',
          select: true
        },
        {
          name: '季卡',
          money: '',
          time: '90',
          select: false
        },
        {
          name: '年卡',
          money: '',
          time: '365',
          select: false
        }],
        totalPay: 0
      })
    }
  },
  /**
   * 选择车场
   */
  selectPark(e) {
    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let checkParkList = this.data.checkParkList

    let selctPark
    if (type == 'history') {
      selctPark = this.data.searcheRecordDiy[index]
    } else if (type == 'nearby') {
      selctPark = this.data.nearbyParkList[index]
    } else {
      selctPark = this.data.searchResult[index]
    }
    if (selctPark.hasMonthRule == 0) {
      Toast('当前停车场暂未开通服务')
      return
    }
    for (var i = 0; i < checkParkList.length; i++) {
      if (selctPark.id == checkParkList[i].id) {
        wx.showToast({
          title: '请不要选择重复停车场',
          icon: 'none'
        })
        return
      }
    }
    checkParkList = checkParkList.concat(selctPark)
    if (checkParkList.length > 5) {
      Toast('最多选择五个停车场')
      return
    }
    let diyCardList = this.data.diyCardList
    for (let i = 0; i < diyCardList.length; i++) {
      diyCardList[i].select = false
    }
    console.log(checkParkList);
    this.setData({
      checkParkList: checkParkList,
      diyCardIndex: 0
    })
    if (checkParkList.length > 1) {
      this.calculateDiyPrice()
    } 
    // else {
    //   this.getMonthPayRule(checkParkList[0].id)
    // }
    this.hiddenSearchDialog()
  },
  /**
  * 计算定制价格
  */
  calculateDiyPrice() {
    let that = this
    let checkParkList = that.data.checkParkList
    let parkIdArr = []
    let diyCardList = that.data.diyCardList
    for (var i = 0; i < checkParkList.length; i++) {
      parkIdArr.push(checkParkList[i].id)
    }
    let url = '/promotion/customize-rule/computePrice'
    let params = {
      parkIds: parkIdArr
    }
    request.http(url, 'POST', params)
      .then(res => {
        let data = res.data
        if (data.code == 200) {
          diyCardList[0].money = data.data.monthTotalAmount
          diyCardList[0].sumAmount = data.data.monthTotalAmount
          diyCardList[0].customizeRuleId = data.data.customizeRuleId
          diyCardList[0].time = data.data.monthDays
          diyCardList[1].money = data.data.quarterTotalAmount
          diyCardList[1].sumAmount = data.data.quarterTotalAmount
          diyCardList[1].customizeRuleId = data.data.customizeRuleId
          diyCardList[1].time = data.data.quarterDays
          diyCardList[2].money = data.data.yearTotalAmount
          diyCardList[2].sumAmount = data.data.yearTotalAmount
          diyCardList[2].customizeRuleId = data.data.customizeRuleId
          diyCardList[2].time = data.data.yearDays
          for (var i = 0; i < diyCardList.length; i++) {
            if (diyCardList[i].sumAmount) {
              diyCardList[i].select = true
              break
            }
          }
          that.setData({
            diyCardList: diyCardList,
            totalPay: diyCardList[0].sumAmount ? diyCardList[0].sumAmount : diyCardList[1].sumAmount ? diyCardList[1].sumAmount : diyCardList[2].sumAmount
          })
        }
      })
  },
  /**
  * 在地图中打开历史搜索位置
  */
  historyToMap(e) {
    let index = e.currentTarget.dataset.index;
    let parkData = this.data.searcheRecordDiy[index]
    let latitude = Number(parkData.latitude)
    let longitude = Number(parkData.longitude)
    wx.openLocation({
      latitude,
      longitude,
      name: parkData.parkName,
      address: parkData.parkAddress,
      scale: 14
    })
  },
  /**
  * 获取月卡支付规则
  */
  getMonthPayRule(id) {
    var that = this
    let diyCardList = that.data.diyCardList
    let url = '/promotion/month-rule-paytype/getMonthRulePaytypeByParkId'
    let params = {
      parkId: id ? id : that.data.nowParkList ? that.data.nowParkList.id : 0
    }
    request.http(url, 'GET', params)
      .then((res) => {
        var data = res.data
        if (data.code == '200') {
          var monthPayRule = data.data
          monthPayRule.sort((a, b) => a.days - b.days); //按月季年排序
          if (data.data.length > 0) {
            for (var i = 0; i < monthPayRule.length; i++) {
              if (i == 0) {
                monthPayRule[i]['select'] = true
              } else {
                monthPayRule[i]['select'] = false
              }
            }
          }
          if (id) {
            for (var i = 0; i < data.data.length; i++) {
              let index = data.data[i].monthRentType == '1' ? 0 : data.data[i].monthRentType == '2' ? 1 : 2
              diyCardList[index].money = data.data[i] ? data.data[i].amount : ''
              diyCardList[index].sumAmount = data.data[i] ? data.data[i].sumAmount : ''
              diyCardList[index].customizeRuleId = data.data[i] ? data.data[i].monthRuleId : ''
              diyCardList[index].time = data.data[i] ? data.data[i].days : ''
              diyCardList[index].monthRuleId = data.data[i] ? data.data[i].monthRuleId : ''
            }
            for (var i = 0; i < diyCardList.length; i++) {
              if (diyCardList[i].sumAmount) {
                diyCardList[i].select = true
                break
              }
            }
            that.setData({
              diyCardList: diyCardList
            })
            if (that.data.tabbarIndex == 1) {
              that.setData({
                totalPay: diyCardList[0].sumAmount ? diyCardList[0].sumAmount : diyCardList[1].sumAmount ? diyCardList[1].sumAmount : diyCardList[2].sumAmount
              })
            }
          } else {
            that.setData({
              monthPayRule
            })
          }
        }
      })
      .catch(res => {
        that.setData({
          monthPayRule: []
        })
      })
  },
  /**
   * 选择月卡
   * @param {*} event 
   */
  cardCheck(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let monthPayRule = that.data.monthPayRule; //通用会员卡列表

    for (let i = 0; i < monthPayRule.length; i++) {
      if (i == index) {
        monthPayRule[i].select = true
      } else {
        monthPayRule[i].select = false
      }
    }
    that.setData({
      monthPayRule: monthPayRule,
      isCard: true,
      cardIndex: index,
      timeIndex: -1,
      isDiy: false,
      totalPay: monthPayRule[index].sumAmount
    })
  },
  /**
  * 选择定制月卡
  */
  checkDiyCard(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let cardList = that.data.cardList; //通用会员卡列表
    let diyCardList = that.data.diyCardList;
    for (let i = 0; i < diyCardList.length; i++) {
      if (i == index) {
        diyCardList[i].select = true
      } else {
        diyCardList[i].select = false
      }
    }
    that.setData({
      cardList: cardList,
      isCard: true,
      diyCardIndex: index,
      diyCardList: diyCardList,
      isDiy: true,
      totalPay: diyCardList[index].sumAmount
    })
  },
  /**
 * 用户协议弹窗
 */
  showAgreement(e) {
    let type = e.currentTarget.dataset.type
    this.setData({
      agreementShow: true,
      agreementType: type
    })
  },
  /**
   * 关闭用户协议弹窗
   */
  showAgreementClose() {
    this.setData({
      agreementShow: false
    })
  },
  /**
   * 同意协议按钮事件
   */
  showAgreementCloseEvent(e, a) {
    let agreement = e.detail
    this.setData({
      agreementVip: agreement
    })
  },
  /**
 * 获取用户信息
 */
  getUserInfo() {
    let that = this;
    let url = '/customer/info/getCustomerInfo'
    request.http(url, 'GET')
      .then((res) => {
        if (res.data.code == 200) {
          let user = res.data.data;
          if (user != null && user != undefined) {
            let phone = user.mobilePhone;
            that.setData({
              mobilePhone: phone
            })
          }
        } else {
          Toast.fail('获取数据失败');
        }
      })
  },
  /**
   * 获取手机号
   * @param {*} e 
   */
  getPhoneNumber: function (e) {
    var that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      let encryptedData = e.detail.encryptedData;
      let iv = e.detail.iv;
      wx.login({
        success(res) {
          let url = '/customer/info/bindMobilePhone'
          let params = {
            code: res.code,
            encryptedData: encryptedData,
            iv: iv
          }
          request.http(url, 'GET', params)
            .then(res => {
              if (res.data.code == 200) {
                let phone = res.data.data
                Toast.success('绑定成功');
                that.setData({
                  mobilePhone: phone
                })
                that.checkPop()
              }
            })
        }
      })
    }
  },
  /**
 * 跳转支付页
 */
  toPayment() {
    if (!this.data.agreementVip) {
      wx.showToast({
        title: '请先阅读并同意会员服务协议',
        icon: 'none'
      })
      return
    }
    let diyCardIndex = this.data.diyCardIndex
    let diyParkList = this.data.checkParkList;
    let diyCardList = this.data.diyCardList;
    let checkParkList = this.data.checkParkList;
    let data = {}
    if (diyParkList.length <= 0) {
      wx.showToast({
        title: '请先添加停车场',
        icon: 'none'
      })
      return
    }
    if (!diyCardList[diyCardIndex]) {
      wx.showToast({
        title: '请选择定制月卡规则',
        icon: 'none'
      })
      return
    }
    if (!diyCardList[diyCardIndex].sumAmount) {
      if (diyCardIndex == 0) {
        diyCardIndex = 1
      }
    }
    data = {
      paidAmount: diyCardList[diyCardIndex].sumAmount,
      monthRentType: diyCardIndex == 0 ? '1' : diyCardIndex == 1 ? '2' : '3',
      parkList: checkParkList,
      type: 'CUSTOMIZE'
    }
    if (diyParkList.length == 1) {
      data['type'] = 'MONTH'
      data['monthRuleId'] = diyCardList[diyCardIndex].monthRuleId
      data['parkList'] = checkParkList[0]
    }
    wx.navigateTo({
      url: '/pages/confirmOrder/confirmOrder?payData=' + JSON.stringify(data),
    })
  }
})